import { SequelizeModel, SmsCodeModel, UserModel, AuthLogModel } from '@model'
import { success, error } from '@res'
const Core = require('@alicloud/pop-core')
import moment from 'moment'
import request from 'request'


const Sequelize = require('sequelize')
const Op = Sequelize.Op

class User {
  // post请求封装
  static fetchPost(url, data) {
    return new Promise((reslove, reject) => {
      const options = {
        url: url,
        qs: data,
        headers: {
          "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
          "Authorization": "APPCODE c19b3b9138f74d21beacae92b5ddf1f0"
        },
        form: data
      }
      request.post(options, function (error, response, body) {
        reslove(JSON.parse(body))
      })
    })
  }
  // 过期时间
  static getExpiredTime() {
    return new Date(Date.parse(moment(moment().valueOf() - 5 * 60 * 1000).format('YYYY-MM-DD HH:mm:ss')))
  }
  // 生产验证码
  static createCode() {
    var arr = [];//容器
    for (var i = 0; i < 6; i++) {//循环六次
      var num = Math.random() * 9;//Math.random();每次生成(0-1)之间的数;
      num = parseInt(num, 10);
      arr.push(num);
    }
    return arr.join('')
  }

  // 发送短信验证码
  static async getSmsCode(ctx) {
    const smsCodeResult = await SmsCodeModel.findOne({
      where: {
        phone: ctx.request.body.phone,
        createdAt: {
          [Op.gt]: this.getExpiredTime()
        }
      }
    })
    if (smsCodeResult) {
      ctx.body = error('短信验证码已发送过，请等待5分钟后获取')
      return
    }
    const code = this.createCode()
    var client = new Core({
      accessKeyId: 'LTAI4GCExEUUY6KEUBrWAZ1u',
      accessKeySecret: 'WAwLH9VYJwEQCY42VnOEBwJQHblyJL',
      endpoint: 'https://dysmsapi.aliyuncs.com',
      apiVersion: '2017-05-25'
    });

    var params = {
      "RegionId": "cn-hangzhou",
      PhoneNumbers: ctx.request.body.phone,
      SignName: '山东暴龙网络科技有限公司',
      TemplateCode: 'SMS_189623172',
      AccessKeyId: 'LTAI4GCExEUUY6KEUBrWAZ1u',
      Action: 'SendSms',
      TemplateParam: JSON.stringify({
        code: code
      })
    }

    var requestOption = {
      method: 'POST'
    };

    // 发送验证码
    const result = await client.request('SendSms', params, requestOption)
    if (result.Code === 'OK') {
      await SmsCodeModel.create({
        phone: ctx.request.body.phone,
        code: code
      })
      ctx.body = success()
    } else {
      ctx.body = error('短信验证码发送失败')
    }
  }

  // 用户登录
  static async login(ctx) {
    const params = ctx.request.body
    console.log(params)
    const smsCodeResult = await await SmsCodeModel.findOne({
      where: {
        phone: params.phone,
        code: params.code,
        createdAt: {
          [Op.gt]: this.getExpiredTime()
        }
      }
    })
    if (!smsCodeResult) {
      ctx.body = error('短信验证码错误或已过期')
      return
    }
    const userResult = await UserModel.findOne({
      where: {
        phone: params.phone
      }
    })
    if (userResult) {
      ctx.body = success(userResult)
      return
    }
    const result = await UserModel.create({
      phone: params.phone
    })
    ctx.body = success(result)
  }

  // 认证身份信息
  static async authInfo(ctx) {
    const params = ctx.request.body
    const result = await this.fetchPost('https://mobile3elements.shumaidata.com/mobile/verify_real_name', {
      idcard: params.idcard,
      mobile: params.mobile,
      name: params.name
    })
    console.log(result)
    if (result.code !== '0') {
      await AuthLogModel.create({
        uid: params.uid,
        type: 1,
        text: JSON.stringify(result),
        status: false
      })
      ctx.body = error(result.message)
      return
    } else {

    }
    console.log(result)
  }
}

export default User